<?php

namespace App\Http\Middleware;

use App\Exceptions\ExceptionCode;
use App\Http\Responses\RespondsJson;
use Closure;
use Illuminate\Support\Facades\Log;

class Sign
{
    use RespondsJson;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestData = $request->request->all();
        Log::debug($requestData);

		if (isset($requestData['url'])) {
			unset($requestData['url']);
		}
//		if (!empty($requestData['mfSign'])) {
        if (empty($requestData['Timestamp'])) {
            return $this->respondJson(['code' => ExceptionCode::GENERAL, 'message' => '时间戳为空']);
        }
        $sign = $requestData['mfSign'];
        unset($requestData['mfSign']);
        //加密开始啦
        ksort($requestData);  //按参数名对参数进行升序排序
        $pStr2 = '';
        foreach ($requestData as $k => $v) {
            $pStr2 .= $k . '=' . $v . '&';
        }  //得到排序后的所有参数名及参数值连接字符串

        $newSign = strtoupper(md5($pStr2 . config('user.sign_secret')));//对排序后的参数及密钥进行MD5加密
        if ($newSign === $sign) {
            $request->request->set('signed', 'true');
        } else {
            return $this->respondJson(['code' => ExceptionCode::GENERAL, 'message' => '验签失败']);
        }

        return $next($request);
    }
}
